package com.zhairuihao.image;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Ret;
import com.qiniu.util.Auth;
import com.zhairuihao.blog.BlogInterceptor;
import com.zhairuihao.classc.ClassService;
import com.zhairuihao.common.model.Blog;
import com.zhairuihao.common.model.Classc;
import com.zhairuihao.common.model.Image;

import java.util.List;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法 详见 JFinal 俱乐部: http://jfinal.com/club
 *
 * <p>所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
public class ImageController extends Controller {

    @Inject
    ImageService service;

    public void page(long classId) {
        classId = getParaToInt("classId");
        renderJson(Ret.ok("data", service.paginate(classId, getParaToInt(0, 1), 50)));
    }

    public void like() {
        renderJson(Ret.ok("data", service.like(getParaToInt())));
    }

    public void download() {
        renderJson(Ret.ok("data", service.download(getParaToInt())));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中， 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    public void save() {
        String para = getPara();
        String pwd = "047";
        if (!pwd.equals(para)) {
            renderJson(Ret.fail());
            return;
        }
        String json = getRawData();
        List<JSONObject> list = FastJson.getJson().parse(json, List.class);
        for (JSONObject object : list) {
            Image image = object.toJavaObject(Image.class);
            image.save();
        }
        renderJson(Ret.ok());
    }

    public void edit() {
        setAttr("image", service.findById(getParaToInt()));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中， 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    public void update() {
        String json = getRawData();
        Image user = FastJson.getJson().parse(json, Image.class);
        Image byId = service.findById(user.getId());
        byId.setClassId(user.getClassId());
//        byId.setUrl(byId.getUrl());
        byId.update();
        renderJson(Ret.ok());
    }

    public void delete() {
        service.deleteById(getParaToInt());
//        renderJson(Ret.ok());
        redirect("/admin/images");
    }

    public void token() {
        String accessKey = "Saa_X9bf7Lg91yDkFuux94h0HwNuafi6lSOB4eBA";
        String secretKey = "2mhvVli7cA0nsYITmA6pX37WWE7teXQhLe5sL0fc";
        String bucket = "zhairuihao-blog";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println(upToken);
        renderJson(Ret.ok("uptoken", upToken));
    }

}
